import React, {createContext, useState} from "react";

import classNames from "classnames";
import {MeunItemProps} from './MeunItem'


export interface MenuProps {
  defIndex: number
  className?: string
  mode?: 'horizontal' | 'vertical'
  style?: React.CSSProperties
  onSelect?: (selectIndex: number) => void
}
interface MeunSonComponentsType {
  Item: React.FC
}

type MeunSonComponents<T> = Partial<MeunSonComponentsType> & React.FC<T>

export interface setSonItem {
  onSelect?: (selectIndex: number) => void
  index: number,
  propsMode?: 'horizontal' | 'vertical' | undefined
}

export const meunContext = createContext<setSonItem>({
  index: 0
})

const Menu: MeunSonComponents<MenuProps> = (props) => {
  const {
    defIndex,
    className,
    mode,
    style,
    onSelect,
    children
  } = props

  const [meunDefIndex, setMeunDefIndex] = useState<number>(defIndex)
  const [propsMode, setPropsMode] = useState(mode)

  const propsUpdateFun = (index: number) => {
    console.log('11', index)
    setMeunDefIndex(index)
    if (onSelect) {
      onSelect(index)
    }
  }

  const propsValues: setSonItem = {
    onSelect: propsUpdateFun,
    index: meunDefIndex,
    propsMode
  }



  const classos = classNames('meun', className ,{
    'meun-vertical': mode === "vertical",
    'meun-horizontal': mode === 'horizontal'
  })

  const renderChildren = () => {
    return React.Children.map(children, (child, index) => {
      const cc = child as React.FunctionComponentElement<MeunItemProps>
      const {displayName} = cc.type
      if (displayName === 'MeunItem') {
        return React.cloneElement(cc, {
          index: index
        })
      } else {
        console.error('请传入MenuItem组件')
      }
    })
  }
  return (
    <ul className={classos} style={style}>
      <meunContext.Provider value={propsValues}>
        {renderChildren()}
      </meunContext.Provider>
    </ul>
  )
}

Menu.defaultProps = {
  defIndex: 0,
  mode: 'horizontal'
}




export default Menu